class WeightProcessor {
  constructor() {
    this.listeners = [];
    this.FirstCurrentWeight = 0;
  }

  // 辅助方法：将十六进制字符串转换为字节数组
  static hexStringToByteArray(hexString) {
    const result = [];
    for (let i = 0; i < hexString.length; i += 2) {
      result.push(parseInt(hexString.substr(i, 2), 16));
    }
    return new Uint8Array(result);
  }

  // 辅助方法：将字节数组转换为十六进制字符串
  static byteArrayToHexString(byteArray) {
    return Array.from(byteArray)
      .map(byte => (byte & 0xff).toString(16).padStart(2, '0'))
      .join('');
  }

  addListener(listener) {
    this.listeners.push(listener);
  }

  removeListener(listener) {
    const index = this.listeners.indexOf(listener);
    if (index > -1) {
      this.listeners.splice(index, 1);
    }
  }

  processWeightData(byteData) {
    // const joinToString = this.processReceivedData(byteData);
    // console.log('joinToString ', joinToString);

    const joinToString = '01032000000000ffefffff000000000000000000000000000000000000000000000000a6d9';
    const indexOf = joinToString.indexOf('0103') / 2;

    if (indexOf >= 0 && indexOf + 35 <= joinToString.length) {
      const dataArrayList = [];
      // const data = joinToString.slice(indexOf + 4, indexOf + 36);

      const data = [0x19, 0x00, 0x00, 0x00];
      const weight = this.calculateWeight(data, 0);
      console.log(`第一路实时重量, weight: ${weight}, i: ${0}`);
      dataArrayList.push({
        way: 1,
        weight: weight
      });

      // for (let i = 0; i <= 7; i++) {
      //   const weight = this.calculateWeight(data, i * 4);
      //   if (i === 0) {
      //     this.FirstCurrentWeight = weight;
      //     console.log(`第一路实时重量, weight: ${weight}, i: ${i}`);
      //   }
      //   dataArrayList.push({
      //     way: i + 1,
      //     weight: weight
      //   });
      // }

      return dataArrayList;
      // 递归处理剩余数据
      // const remainingData = byteData.slice(indexOf + 35);
      // return this.processWeightData(remainingData);
    } else {
      // 通知监听器接收到原始数据
      this.listeners.forEach(listener => {
        if (listener.onDataReceived) {
          listener.onDataReceived(byteData);
        }
      });
      return byteData;
    }
  }

  string2byte(str) {
    let ch,
      st,
      re = [];
    for (let i = 0; i < str.length; i++) {
      ch = str.charCodeAt(i); // get char
      st = []; // set up "stack"
      do {
        st.push(ch & 0xff); // push byte to stack
        ch = ch >> 8; // shift value down by 1 byte
      } while (ch);
      // add stack contents to result
      // done because chars have "wrong" endianness
      re = re.concat(st.reverse());
    }
    // return an array of bytes
    return re;
  }

  // 处理接收到的数据
  processReceivedData(arrayBuffer) {
    try {
      // 转换为Uint8Array进行处理
      const byteArray = new Uint8Array(arrayBuffer);

      // 转换为十六进制字符串查看
      const hexString = Array.from(byteArray)
        .map(byte => byte.toString(16).padStart(2, '0'))
        .join('');

      return hexString;
    } catch (error) {
      console.error('处理数据出错:', error);
    }
  }

  normalizeByteData(byteData) {
    if (byteData instanceof Uint8Array) {
      return byteData;
    } else if (byteData instanceof ArrayBuffer) {
      return new Uint8Array(byteData);
    } else if (Array.isArray(byteData)) {
      return new Uint8Array(byteData);
    } else if (typeof byteData === 'string') {
      // 如果是十六进制字符串，转换为字节数组
      return this.hexStringToByteArray(byteData);
    } else {
      console.error('不支持的字节数据类型:', typeof byteData, byteData);
      return null;
    }
  }

  hexStringToByteArray(hexString) {
    const result = [];
    for (let i = 0; i < hexString.length; i += 2) {
      result.push(parseInt(hexString.substr(i, 2), 16));
    }
    return new Uint8Array(result);
  }

  /**
   * 计算单路重量
   * @param {string} bytes - 重量数据字节数组
   * @param {number} startIndex - 起始索引
   * @returns {number} 重量值
   */
  calculateWeight(bytes, startIndex) {
    // 确保索引在有效范围内
    if (startIndex + 3 >= bytes.length) {
      console.error('索引超出范围');
      return 0;
    }

    // const byte0 = this.string2byte(bytes[startIndex]) & 0xff;
    // const byte1 = this.string2byte(bytes[startIndex + 1]) & 0xff;
    // const byte2 = this.string2byte(bytes[startIndex + 2]) & 0xff;
    // const byte3 = this.string2byte(bytes[startIndex + 3]) & 0xff;

    const byte0 = bytes[startIndex] & 0xff;
    const byte1 = bytes[startIndex + 1] & 0xff;
    const byte2 = bytes[startIndex + 2] & 0xff;
    const byte3 = bytes[startIndex + 3] & 0xff;

    // console.log('字符串转字节', this.string2byte(bytes[startIndex]));

    console.log(`第${startIndex / 4 + 1}路原始字节:`, byte0, byte1, byte2, byte3);

    if (byte3 === 0) {
      // 正数计算
      const highPart = (byte2 * 256 + byte3) * 65536; // (byte2 * 256 + byte3) * 65536
      const lowPart = byte0 * 256 + byte1; // byte0 * 256 + byte1
      const weight = highPart + lowPart;

      console.log(`正数计算: (${byte2}*256+${byte3})*65536 + ${byte0}*256+${byte1} = ${weight}`);
      return weight;
    } else {
      // const two0 = byte0.toString(2).padStart(8, '0');
      // const two1 = byte1.toString(2).padStart(8, '0');
      // const two2 = byte2.toString(2).padStart(8, '0');
      // const two3 = byte3.toString(2).padStart(8, '0');
      // console.log(`第${startIndex / 4 + 1}路二进制:`, two0, two1, two2, two3);

      // 负数计算（补码）
      // const data3 = Number(bytes[startIndex]);
      // const data4 = Number(bytes[startIndex + 1]);
      // const data5 = Number(bytes[startIndex + 2]);
      // const data6 = Number(bytes[startIndex + 3]);

      // const data4 = parseInt(String(two1 ^ 0xff), 2);
      // const data5 = parseInt(String(two2 ^ 0xff), 2);
      // const data6 = parseInt(String(two3 ^ 0xff), 2);

      // const data4 = two1 ^ 0xff; // bytes[startIndex + 1] 异或
      // const data5 = two2 ^ 0xff; // bytes[startIndex + 2] 异或
      // const data6 = two3 ^ 0xff; // bytes[startIndex + 3] 异或
      // console.log(`第${startIndex / 4 + 1}路补码:`, data3, data4, data5, data6);

      const data3 = this.kotlinStyleConversion(bytes[startIndex]);
      const data4 = this.kotlinStyleConversion(bytes[startIndex + 1]);
      const data5 = this.kotlinStyleConversion(bytes[startIndex + 2]);
      const data6 = this.kotlinStyleConversion(bytes[startIndex + 3]);

      const value = (data5 * 256 + data6) * 65536 + data3 * 256 + data4 + 1;
      const weight = -value;

      console.log(`负数计算: -(((${data5}*256+${data6})*65536 + ${data3}*256+${data4}+1)) = ${weight}`);
      return weight;
    }
  }

  // 模拟 HexUtil.toByteString().toInt(16) 的过程
  kotlinStyleConversion(byte) {
    // 1. 将字节转换为十六进制字符串
    const hexString = byte.toString(16).padStart(2, '0');
    console.log(`字节 0x${byte.toString(16).padStart(2, '0')} -> 字符串 "${hexString}"`);

    // 2. 将十六进制字符串解析为整数
    const intValue = parseInt(hexString, 16);
    console.log(`字符串 "${hexString}" -> 整数 ${intValue}`);

    // 3. 与 0xFF 异或
    const result = intValue ^ 0xff;
    console.log(`整数 ${intValue} ^ 0xFF = ${result} (0x${result.toString(16)})`);

    return result;
  }
}

export default new WeightProcessor()


// 处理重量数据
// const byteData = new Uint8Array([...]); // 你的字节数据
// const result = processor.processWeightData(byteData);
